<template>
  <div class="permission">
    <el-card>
      <pageTools>
        <template #right>
          <el-button
            type="primary"
            @click="addMenu(1, '0')"
          >添加菜单</el-button>
        </template>
      </pageTools>
      <!-- table 中树形数据结构需要满足两点
 1. 数据中有children子级
 2. 添加 row-key="标识"  唯一标识符
  -->
      <el-table
        :data="list"
        style="width: 100%"
        row-key="id"
        default-expand-all
      >
        <el-table-column prop="name" label="菜单名称" />
        <el-table-column prop="code" label="权限标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <div>
              <span v-if="row.type === 1" style="margin-right: 10px">
                <el-button
                  type="text"
                  @click="addMenu(1, row.id)"
                >添加页面</el-button>
                <el-button
                  type="text"
                  @click="addMenu(2, row.id)"
                >添加按钮</el-button>
              </span>
              <el-button type="text" @click="edit(row)">编辑权限点</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <Add ref="add" @getData="getData" />
  </div>
</template>

<script>
import { sysPermission, sysPermissionDel } from '@/api/permission'
import { treeData } from '@/utils/index'
import Add from './components/Add.vue'
export default {
  components: {
    Add
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const { data } = await sysPermission()
      this.list = treeData(data, '0')
      // console.log(this.list)
    },
    addMenu(type, pid) {
      // 根据不同按钮传递的参数决定添加的是页面还是按钮
      this.$refs.add.isShow = true
      this.$refs.add.mode = 'add'
      this.$refs.add.form.type = type
      this.$refs.add.form.pid = pid
    },
    // 删除
    del(id) {
      this.$confirm('确定删除该项吗', '提示')
        .then(async() => {
          await sysPermissionDel(id)
          this.$message.success('删除成功')
          this.getData()
        })
        .catch(() => {})
    },
    // 编辑
    edit(row) {
      this.$refs.add.isShow = true
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
      this.$refs.add.mode = 'edit'
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 15px;
}
</style>
